package com.gitee.mars.marsquickframe.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gitee.mars.marsquickframe.entity.SysRoleMenu;
import com.gitee.mars.marsquickframe.mapper.SysRoleMenuMapper;
import com.gitee.mars.marsquickframe.response.base.BasePageRequest;
import com.gitee.mars.marsquickframe.service.SysRoleMenuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 实现层
 *
 * @Author wq
 * @Date 2020-12-15
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {

    @Override
    public IPage<SysRoleMenu> page(BasePageRequest query) {
        IPage<SysRoleMenu> page = new Page<>(query.getPageNumber(), query.getPageSize());
        return baseMapper.findByQuery(page, query);
    }

    @Override
    public void saveRelation(Integer roleId, Set<Integer> menuIds) {
        List<SysRoleMenu> menuList = menuIds.stream().map(x -> {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setMenuId(x);
            sysRoleMenu.setRoleId(roleId);
            return sysRoleMenu;
        }).collect(Collectors.toList());
        saveBatch(menuList);
    }

    @Override
    public void delRelation(Integer roleId) {
        baseMapper.delete(new QueryWrapper<SysRoleMenu>().lambda()
                .eq(SysRoleMenu::getRoleId, roleId));
    }

    @Override
    public List<Integer> findRelation(Integer roleId) {
        //根据角色ID查询菜单集合
        List<SysRoleMenu> list = list(new LambdaQueryWrapper<SysRoleMenu>()
                .eq(SysRoleMenu::getRoleId, roleId));
        return list.stream()
                .map(SysRoleMenu::getMenuId)
                .collect(Collectors.toList());
    }

}